// pages/result/result.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cocktailInfo: {
      name: '欢悦气泡',
      subtitle: '专属于你的夏日清爽特调',
      image: 'https://images.unsplash.com/photo-1536935338788-846bb9981813?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1886&q=80',
      ingredients: [
        '意大利普罗塞克起泡酒 (100ml)',
        '柠檬汁 (15ml)',
        '薄荷叶碎 (5g)',
        '少量苏打水 (10ml)',
        '橙片装饰 + 彩色纸风车'
      ],
      taste: '仿佛夏日微风拂过舌尖，柠檬的酸甜如同欢快的音符，薄荷叶则带来丝丝清凉，口感轻盈如舞。',
      guide: '冷藏后饮用，用高脚杯，轻轻搅拌，感受气泡在舌尖跳跃。',
      health: '约合2.5标准杯 | 无酒精替代可选用气泡水+柠檬汁 | 适合任何年龄段饮用',
      setting: '户外野餐 | 搭配彩色气球与鲜花 | 背景音乐为欢快的流行曲',
      story: '起泡酒起源于意大利，以其丰富的气泡和清爽口感而闻名。在欢乐的时刻，起泡酒就像生活中的小惊喜，带来无尽的愉悦。'
    },
    perfumeInfo: null,
    isCollected: false,
    historyImages: [
      'https://images.unsplash.com/photo-1615887029950-3051870bcc84?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1756&q=80',
      'https://images.unsplash.com/photo-1551024709-8f23befc6f87?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1778&q=80'
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.source === 'perfume') {
      let perfumeData = {};
      try {
        perfumeData = options.data ? JSON.parse(decodeURIComponent(options.data)) : {};
      } catch (e) {
        perfumeData = {};
      }
      this.setData({
        perfumeInfo: {
          name: perfumeData.perfumeName || '专属香水',
          image: perfumeData.outfitImage || '',
          ingredients: this.formatPerfumeIngredients(perfumeData.ingredients),
          guideline: perfumeData.guideline || {},
          story: perfumeData.story || ''
        }
      });

      // === 自动保存香水推荐到后端，带 category 字段 ===
      if (perfumeData.perfumeName && perfumeData.outfitImage) {
        wx.request({
          url: 'http://localhost:3000/api/history', // 替换为你的服务器地址
          method: 'POST',
          data: {
            name: perfumeData.perfumeName,
            image: perfumeData.outfitImage,
            userId: '', // 如有用户ID可填写
            type: 'auto',
            category: 'perfume'
          },
          success(res) {
            console.log('香水历史推荐已保存', res.data);
          }
        });
      }
      // === 新增结束 ===

      console.log('perfumeInfo.ingredients:', this.data.perfumeInfo.ingredients);
      return;
    } else if (options.source === 'api') {
      // 从API获取的数据
      const app = getApp();
      if (app.globalData && app.globalData.cocktailResult) {
        this.setData({
          cocktailInfo: app.globalData.cocktailResult
        });
        
        // 保存到历史记录
        this.saveToHistory(app.globalData.cocktailResult);
        
        // 检查是否已经收藏过
        this.checkIfCollected(app.globalData.cocktailResult.name);
      }
    } else if (options.apiData) {
      // 直接处理API返回的数据（JSON格式的字符串）
      try {
        const apiData = JSON.parse(options.apiData);
        const cocktailData = this.processApiData(apiData);
        
        this.setData({
          cocktailInfo: cocktailData
        });
        
        // 保存到历史记录
        this.saveToHistory(cocktailData);
        
        // 检查是否已经收藏过
        this.checkIfCollected(cocktailData.name);
        
        // 同时保存到全局数据，以便其他页面使用
        const app = getApp();
        app.globalData = app.globalData || {};
        app.globalData.cocktailResult = cocktailData;
      } catch (e) {
        console.error('解析API数据失败:', e);
        wx.showToast({
          title: '数据解析失败',
          icon: 'none'
        });
      }
    } else if (options.id) {
      // 如果有id参数，从历史记录或收藏中加载对应的配方
      this.loadCocktailById(options.id);
    }
  },
  
  /**
   * 处理API返回的数据
   */
  processApiData: function(apiData) {
    // apiData是从API返回的原始数据
    let apiResult;
    
    // 尝试获取和解析数据对象
    if (typeof apiData === 'string') {
      try {
        apiResult = JSON.parse(apiData);
      } catch(e) {
        apiResult = apiData;
      }
    } else if (apiData.data) {
      // 如果已经是对象并且有data字段
      try {
        apiResult = typeof apiData.data === 'string' ? JSON.parse(apiData.data) : apiData.data;
      } catch(e) {
        apiResult = apiData.data;
      }
    } else {
      apiResult = apiData;
    }
    
    // 提取所需数据并格式化
    return {
      name: apiResult.cocktailName || '今日精选特调',
      subtitle: apiResult.subtitle || `专属特调`,
      image: apiResult.data || apiResult.imageUrl || 'https://images.unsplash.com/photo-1536935338788-846bb9981813',
      cost: apiResult.cost || '',
      ingredients: this.formatIngredients(apiResult.formula),
      taste: apiResult.formula?.tasteProfile || '这款鸡尾酒口感清爽怡人，甜酸适中，回味悠长。入口甘醇，略带果香，余韵中蕴含微妙的草本气息。',
      guide: apiResult.guideline?.drinkingMethod || '建议冰镇后饮用，可配以柠檬片或薄荷叶点缀。轻轻摇晃后饮用，以充分体验其独特风味。',
      health: apiResult.guideline?.healthReminder || '酒精含量适中，建议适量饮用。如您正在服药或有特殊健康状况，请咨询医生后饮用。',
      setting: apiResult.guideline?.idealSetting || '非常适合晚间休闲时光或与朋友小聚时享用。搭配轻音乐和温馨灯光效果更佳。',
      story: apiResult.spiritStory || '这款特调灵感源于经典鸡尾酒文化，融合现代调酒工艺，为您带来独特的味蕾体验。每一口都蕴含调酒师的匠心与热情。'
    };
  },
  
  /**
   * 格式化配方成数组
   */
  formatIngredients: function(formula) {
    if (!formula) return ['暂无配方信息'];
    
    const ingredients = [];
    
    // 添加基酒
    if (formula.baseSpirits) {
      const baseSpirits = formula.baseSpirits.split('+').map(item => item.trim());
      ingredients.push(...baseSpirits);
    }
    
    // 添加调味元素
    if (formula.flavorElements) {
      const flavorElements = formula.flavorElements.split('+').map(item => item.trim());
      ingredients.push(...flavorElements);
    }
    
    // 添加装饰
    if (formula.garnish) {
      const garnish = formula.garnish.split('+').map(item => item.trim());
      ingredients.push(...garnish);
    }
    
    return ingredients.length > 0 ? ingredients : ['暂无配方信息'];
  },
  
  /**
   * 从本地存储加载鸡尾酒数据
   */
  loadCocktailById: function(id) {
    try {
      // 尝试从历史记录中加载
      const historyList = wx.getStorageSync('cocktail_history') || [];
      
      if (id >= 0 && id < historyList.length) {
        const item = historyList[id];
        
        if (item) {
          // 处理ingredients数据，确保是数组形式
          let ingredients = item.ingredients;
          if (typeof ingredients === 'string') {
            ingredients = ingredients.split(', ');
          } else if (!Array.isArray(ingredients)) {
            ingredients = ['推荐使用优质基酒搭配新鲜水果调制'];
          }
          
          // 提供更丰富的默认值
          const defaultTaste = '这款鸡尾酒口感清爽怡人，甜酸适中，回味悠长。入口甘醇，略带果香，余韵中蕴含微妙的草本气息。';
          const defaultGuide = '建议冰镇后饮用，可配以柠檬片或薄荷叶点缀。轻轻摇晃后饮用，以充分体验其独特风味。';
          const defaultHealth = '酒精含量适中，建议适量饮用。如您正在服药或有特殊健康状况，请咨询医生后饮用。';
          const defaultSetting = '非常适合晚间休闲时光或与朋友小聚时享用。搭配轻音乐和温馨灯光效果更佳。';
          const defaultStory = '这款特调灵感源于经典鸡尾酒文化，融合现代调酒工艺，为您带来独特的味蕾体验。每一口都蕴含调酒师的匠心与热情。';
          
          this.setData({
            cocktailInfo: {
              name: item.name || '今日精选特调',
              subtitle: item.subtitle || '历史配方',
              image: item.image,
              ingredients: ingredients,
              taste: item.taste || defaultTaste,
              guide: item.guide || defaultGuide,
              health: item.health || defaultHealth,
              setting: item.setting || defaultSetting,
              story: item.story || defaultStory
            }
          });
          
          // 检查是否已收藏
          this.checkIfCollected(item.name);
          return;
        }
      } else {
        // 尝试从收藏中加载
        const collectionList = wx.getStorageSync('cocktail_collection') || [];
        const collectionId = parseInt(id) - 1000; // 使用偏移值区分历史记录和收藏
        
        if (collectionId >= 0 && collectionId < collectionList.length) {
          const item = collectionList[collectionId];
          
          if (item) {
            // 处理ingredients数据，确保是数组形式
            let ingredients = item.ingredients;
            if (typeof ingredients === 'string') {
              ingredients = ingredients.split(', ');
            } else if (!Array.isArray(ingredients)) {
              ingredients = ['推荐使用优质基酒搭配新鲜水果调制'];
            }
            
            // 提供更丰富的默认值
            const defaultTaste = '这款鸡尾酒口感清爽怡人，甜酸适中，回味悠长。入口甘醇，略带果香，余韵中蕴含微妙的草本气息。';
            const defaultGuide = '建议冰镇后饮用，可配以柠檬片或薄荷叶点缀。轻轻摇晃后饮用，以充分体验其独特风味。';
            const defaultHealth = '酒精含量适中，建议适量饮用。如您正在服药或有特殊健康状况，请咨询医生后饮用。';
            const defaultSetting = '非常适合晚间休闲时光或与朋友小聚时享用。搭配轻音乐和温馨灯光效果更佳。';
            const defaultStory = '这款特调灵感源于经典鸡尾酒文化，融合现代调酒工艺，为您带来独特的味蕾体验。每一口都蕴含调酒师的匠心与热情。';
            
            this.setData({
              cocktailInfo: {
                name: item.name || '今日精选特调',
                subtitle: '收藏配方',
                image: item.image,
                ingredients: ingredients,
                taste: item.taste || defaultTaste,
                guide: item.guide || defaultGuide,
                health: item.health || defaultHealth,
                setting: item.setting || defaultSetting,
                story: item.story || defaultStory
              },
              isCollected: true // 从收藏中加载的一定是已收藏状态
            });
            return;
          }
        }
      }
      
      // 如果没有找到数据，使用默认数据（已在data中设置）
    } catch (e) {
      console.error('加载鸡尾酒数据失败:', e);
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  },
  
  /**
   * 检查是否已收藏
   */
  checkIfCollected: function(cocktailName) {
    try {
      const collectionList = wx.getStorageSync('cocktail_collection') || [];
      const isCollected = collectionList.some(item => item.name === cocktailName);
      this.setData({
        isCollected: isCollected
      });
    } catch (e) {
      console.error('检查收藏状态失败:', e);
    }
  },

  /**
   * 保存到历史记录
   */
  saveToHistory: function(cocktailData) {
    try {
      let historyList = wx.getStorageSync('cocktail_history') || [];
      const isExist = historyList.some(item => item.name === cocktailData.name);
      if (!isExist) {
        historyList.unshift({
          name: cocktailData.name,
          subtitle: cocktailData.subtitle,
          image: cocktailData.image,
          ingredients: Array.isArray(cocktailData.ingredients)
            ? cocktailData.ingredients.join(', ')
            : cocktailData.ingredients,
          taste: cocktailData.taste,
          guide: cocktailData.guide,
          health: cocktailData.health,
          setting: cocktailData.setting,
          story: cocktailData.story,
          timestamp: new Date().getTime()
        });
        if (historyList.length > 10) {
          historyList = historyList.slice(0, 10);
        }
        wx.setStorageSync('cocktail_history', historyList);
      }
    } catch (e) {
      console.error('保存历史记录失败:', e);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 结果页面不需要显示TabBar，因为它不是TabBar页面
    // 这里可以添加页面显示时的其他逻辑
  },

  /**
   * 收藏鸡尾酒
   */
  collectCocktail: function() {
    const isCollected = !this.data.isCollected;
    this.setData({
      isCollected: isCollected
    });
    try {
      let collectionList = wx.getStorageSync('cocktail_collection') || [];
      if (isCollected) {
        const cocktailInfo = this.data.cocktailInfo;
        const isExist = collectionList.some(item => item.name === cocktailInfo.name);
        if (!isExist) {
          collectionList.unshift({
            name: cocktailInfo.name,
            subtitle: cocktailInfo.subtitle,
            image: cocktailInfo.image,
            ingredients: Array.isArray(cocktailInfo.ingredients)
              ? cocktailInfo.ingredients.join(', ')
              : cocktailInfo.ingredients,
            taste: cocktailInfo.taste,
            guide: cocktailInfo.guide,
            health: cocktailInfo.health,
            setting: cocktailInfo.setting,
            story: cocktailInfo.story,
            timestamp: new Date().getTime()
          });
          wx.setStorageSync('cocktail_collection', collectionList);
          wx.showToast({
            title: '收藏成功',
            icon: 'success'
          });
        }
      } else {
        const cocktailInfo = this.data.cocktailInfo;
        collectionList = collectionList.filter(item => item.name !== cocktailInfo.name);
        wx.setStorageSync('cocktail_collection', collectionList);
        wx.showToast({
          title: '已取消收藏',
          icon: 'none'
        });
      }
    } catch (e) {
      console.error('收藏操作失败:', e);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  /**
   * 分享鸡尾酒
   */
  shareCocktail: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    
    wx.showToast({
      title: '请点击右上角分享',
      icon: 'none'
    });
  },
  
  /**
   * 返回上一页
   */
  goBack: function() {
    wx.navigateBack({
      delta: 1
    });
  },
  
  /**
   * 导航到历史记录页面
   */
  navigateToHistory: function() {
    wx.navigateTo({
      url: '../history/history'
    });
  },
  
  /**
   * 导航到首页
   */
  navigateToHome: function() {
    wx.switchTab({
      url: '../cocktail/cocktail'
    });
  },
  
  /**
   * 导航到个人中心
   */
  navigateToProfile: function() {
    wx.switchTab({
      url: '../profile/profile'
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.cocktailInfo.name + ' - 今日微醺特调',
      path: '/pages/index/index',
      imageUrl: this.data.cocktailInfo.image
    };
  },
  
  /**
   * 用户点击右上角分享到朋友圈
   */
  onShareTimeline: function () {
    return {
      title: this.data.cocktailInfo.name + ' - 今日微醺特调',
      query: '',
      imageUrl: this.data.cocktailInfo.image
    };
  },

  /**
   * 格式化香水配料成数组
   */
  formatPerfumeIngredients: function(ingredients) {
    if (!ingredients) return [];
    if (typeof ingredients === 'string') {
      return ingredients.split(/[\+,，]/).map(item => item.trim()).filter(Boolean);
    }
    if (Array.isArray(ingredients)) {
      return ingredients;
    }
    if (typeof ingredients === 'object') {
      // 兼容 value 为对象（如 {name, ratio}）的情况
      return Object.keys(ingredients).map(key => {
        const value = ingredients[key];
        if (typeof value === 'object' && value !== null) {
          return {
            name: value.name || key,
            amount: value.ratio || value.amount || ''
          };
        }
        // 兼容 value 为字符串的情况
        return {
          name: key,
          amount: value
        };
      });
    }
    return [];
  }
}) 